package mx.util;

import java.io.IOException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import mx.beans.Console;
import mx.beans.Game;
import mx.beans.Portrait;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.os.AsyncTask;
import android.util.Log;

public class DomGameConstructor extends AsyncTask<URL, Integer, List<Game>> {

	@Override
	protected List<Game> doInBackground(URL... params) {

		List<Game> result = new LinkedList<Game>();

		try {
			URL xmlFile = params[0];
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(xmlFile.openStream());

			doc.getDocumentElement().normalize();

			NodeList nList = doc.getElementsByTagName("game");
			Integer listLength = nList.getLength();

			for (int i = 0; i < listLength; i++) {

				Node node = nList.item(i);
				Element element = (Element) node;

				if (node.getNodeType() == Node.ELEMENT_NODE) {
					Game tmp = new Game(
							getTagValue("SKU", element),
							getTagValue("finalPrice", element), 
							getTagValue("publisher", element), 
							getTagValue("genre",element), 
							getTagValue("gameDetailURL",element), 
							getTagValue("name", element),
							getTagValue("clasification", element));
					
					

					List<Portrait> portraits = DomGameConstructor
							.getPortraits(element, tmp.getName());
					List<Console> consoles = new LinkedList<Console>();

					for (Portrait portrait : portraits) {
						consoles.add(portrait.getConsole());
					}
					
					tmp.setPortraits(portraits);
					tmp.setConsoles(consoles);
					
					result.add(tmp);
					
				}

				
				publishProgress((int) ((i / (float) listLength) * 100));
			}
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;

	}

	private static String getTagValue(String sTag, Element eElement) {

		NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
				.getChildNodes();

		Node nValue = (Node) nlList.item(0);

		return nValue.getNodeValue();
	}

	private static List<Portrait> getPortraits(Element element, String gameName) {

		//TODO CHecar si ya se han guardado previamente para no bajar de nuevo
		//las imágenes
		LinkedList<Portrait> result = new LinkedList<Portrait>();

		NodeList nodeList = element.getElementsByTagName("urlPortrait");

		for (int i = 0; i < nodeList.getLength(); i++) {

			Node consoles = nodeList.item(i);
			
			String consoleName = consoles.getAttributes().getNamedItem("console").getTextContent();
			String urlPortrait = consoles.getChildNodes().item(0).getNodeValue();
			
			result.add(new Portrait(urlPortrait, parseConsole(consoleName), 
					gameName.trim().replace(" ", "") + 
					consoleName.trim().replace(" ", "")));
					
		}

		return result;
	}

	private static Console parseConsole(String nodeValue) {
		if (nodeValue.equals("Xbox 360")) {
			return Console.get(Console.XBox360);
		} else if (nodeValue.equals("Wii U")) {
			return Console.get(Console.Wii);
			// TODO Agregar WII U a las consolas
		}else if (nodeValue.equals("PS3")) {
			return Console.get(Console.PS3);
		} else {
			return Console.get(Console.DEFAULT);
		}
		// TODO Agregar consolas restantes
	}

}
